package com.yitiao.simple.file;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 局域网文件传输
 */
public class FileServer {
    private static String FILE_NAME = "";

    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                            ch.pipeline().addLast(new FileServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture future = bootstrap.bind(8888).sync();
            System.out.println("Server started. Listening on port 8888.");

            future.channel().closeFuture().sync();
            System.out.println("f");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    static class FileServerHandler extends ChannelInboundHandlerAdapter {
        private FileOutputStream fileOutputStream;
        private long startTime;

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
//            fos = new FileOutputStream("./article/file_receive.jpg");
            System.out.println("Client connected.");
            startTime = System.currentTimeMillis();
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            if (msg instanceof ByteBuf) {
                ByteBuf buffer = (ByteBuf) msg;
                if (FILE_NAME.isEmpty()) {
                    FILE_NAME = buffer.toString(io.netty.util.CharsetUtil.UTF_8);
                    System.out.println(FILE_NAME);
//                    fileOutputStream = new FileOutputStream("./article/" + FILE_NAME);
                    buffer.release();
                } else {
                    // 将字节数据写入图片文件
                    byte[] imageData = new byte[buffer.readableBytes()];
                    buffer.readBytes(imageData);
                    Files.write(Paths.get("./data/" + FILE_NAME), imageData);
                    FILE_NAME = "";
                }
            }
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }
}
